/*
 * Copyright 2000-2006 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.gwt.run;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.gwt.GwtConfiguration;
import com.intellij.gwt.make.GwtCompilerPaths;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.VirtualFile;

import java.io.File;

/**
 * @author nik
*/
public class GwtCommandLineState extends JavaCommandLineState {
  private final Module myModule;
  private String myRunPage;
  private String myVMParameters;
  private boolean myNoServer;
  private String myServerUrl;

    public GwtCommandLineState(final Module module, final RunnerSettings runnerSettings, final ConfigurationPerRunnerSettings configurationSettings,
                             final String runPage,
                             final String vmParameters,
                             final boolean noServer,
                             final String serverUrl) {
    super(runnerSettings, configurationSettings);
    myModule = module;
    myRunPage = runPage;
    myVMParameters = vmParameters;
    myNoServer = noServer;
    myServerUrl = serverUrl;
  }

  protected JavaParameters createJavaParameters() throws ExecutionException {
    final JavaParameters params = new JavaParameters();

    //final String moduleDir = new File(myModule.getModuleFilePath()).getParent();
    params.setWorkingDirectory(getTempOutputDir());

    params.configureByModule(myModule, JavaParameters.JDK_AND_CLASSES);

    if (SystemInfo.isMac) {
      params.getVMParametersList().add("-XstartOnFirstThread");
    }
    params.getVMParametersList().addParametersString(myVMParameters);

    final GwtConfiguration configuration = GwtConfiguration.getInstance();

    final ParametersList programParameters = params.getProgramParametersList();
    String runPage;
    if (myNoServer) {
        programParameters.add("-noserver");
        runPage = myServerUrl + myRunPage;
    } else {
        runPage = myRunPage;
    }
    programParameters.add("-style");
    programParameters.add(configuration.getOutputStyle().getId());
    programParameters.add("-out");
    programParameters.add(getOutputPath().getAbsolutePath());
    programParameters.add("-gen");
    programParameters.add(getGenPath().getAbsolutePath());
    programParameters.add(runPage);

    params.getClassPath().addFirst(configuration.getDevJarPath());
    final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(myModule);
    for (VirtualFile src : moduleRootManager.getSourceRoots()) {
      params.getClassPath().addFirst(src.getPath());
    }

    params.setMainClass("com.google.gwt.dev.GWTShell");

    return params;
  }

  @SuppressWarnings({"HardCodedStringLiteral"})
  private File getGenPath() {
    return new File(getTempOutputDir(), "gen");
  }

  @SuppressWarnings({"HardCodedStringLiteral"})
  private File getOutputPath() {
    return new File(getTempOutputDir(), "www");
  }

  @SuppressWarnings({"HardCodedStringLiteral"})
  private File getTempOutputDir() {
    return new File(GwtCompilerPaths.getOutputRoot(myModule), "run");
  }

  public ExecutionResult execute() throws ExecutionException {
    getOutputPath().mkdirs();
    getGenPath().mkdirs();
    final ExecutionResult result = super.execute();
    result.getProcessHandler().addProcessListener(new ProcessAdapter() {
      public void processTerminated(final ProcessEvent event) {
        FileUtil.delete(getTempOutputDir());
      }
    });
    return result;
  }
}
